import requests
import json

# url：https://api.bilibili.com/x/emote/user/panel/web?business=reply


response = requests.get("https://api.bilibili.com/x/emote/user/panel/web?business=reply", headers={
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
                  "Chrome/99.0.4844.51 Safari/537.36 Edg/99.0.1150.39"})


def packages():
    response_json = response.text
    response_dict = json.loads(response_json)
    content_ = response_dict["data"]["packages"]
    del content_[3]
    return content_


if response.status_code == 200:

    content = packages()  # 调用函数

    i = 0
    for object_i in content:  # 取出表情包的每一类，取出的每一类属于字典类型
        object_inside = object_i["emote"]  # 取出字典中的"emote"对应值，里面有表情包的url，字典中的其他项为对表情包分类的描述

        for emote in object_inside:  # "emote"也是一个列表，列表中的每个元素为字典，记录着每个表情包的详细信息

            emote_text, emote_url = emote["text"], emote["url"]  # 取出每个表情包的名称和url，text用来给下载下来的表情包命名，url用于下载表情包
            response_emote = requests.get(emote_url)  # 获取每个表情包的url
            print(f"正在保存表情包{emote_text}")

            if i % 8 == 0:
                with open(f".\\img\\test\\emo_{i}.png", "wb") as f:  # open函数打开文件路径，没有就创建，已有就覆盖，"wb"为写入二进制文件
                    f.write(response_emote.content)  # f.write("写入的信息")
                    i += 1
            else:
                with open(f".\\img\\data\\emo_{i}.png", "wb") as f:  # open函数打开文件路径，没有就创建，已有就覆盖，"wb"为写入二进制文件
                    f.write(response_emote.content)  # f.write("写入的信息")
                    i += 1
